package com.yydream.common.handler;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.handlers.MetaObjectHandler;
import com.yydream.domain.LoginUser;
import com.yydream.entity.SysUserEntity;
import com.yydream.mapper.SysUserMapper;
import lombok.extern.slf4j.Slf4j;
import org.apache.ibatis.reflection.MetaObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.stereotype.Component;

import java.util.Date;
import java.util.Objects;

@Component
@Slf4j
public class SecurityMetaObjectHandler implements MetaObjectHandler {

    @Autowired
    SysUserMapper sysUserMapper;
    @Override
    public void insertFill(MetaObject metaObject) {
        // 获取当前认证信息
        Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
        if (authentication != null && authentication.isAuthenticated()) {
            // 获取认证后的用户信息
            Object principal = authentication.getPrincipal();
            if (!"java.lang.String".equals(principal.getClass().getTypeName())) {
                 LoginUser userDetails = (LoginUser) principal;
                SysUserEntity userEntity = userDetails.getUserEntity();
                if (Objects.nonNull(userEntity)) {
                    // 假设实体类有username属性
                    this.strictInsertFill(metaObject, "createdId", Long.class, userEntity.getId());
                    this.strictInsertFill(metaObject, "updatedId", Long.class, userEntity.getId());
                }
            }
        }
        Date date = new Date();
        this.strictInsertFill(metaObject, "createdTime", Date.class, date);
        this.strictInsertFill(metaObject, "updatedTime", Date.class, date);
    }
 
    @Override
    public void updateFill(MetaObject metaObject) {
        // 同insertFill方法
        // 获取当前认证信息
        Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
        if (authentication != null && authentication.isAuthenticated()) {
            // 获取认证后的用户信息
            LoginUser userDetails = (LoginUser) authentication.getPrincipal();
            // 获取用户名填充到实体属性中
            SysUserEntity userEntity = userDetails.getUserEntity();
            if (Objects.nonNull(userEntity)) {
                // 假设实体类有username属性
                this.strictInsertFill(metaObject, "updatedId", Long.class, userEntity.getId());
            }
        }
        Date date = new Date();
        this.strictInsertFill(metaObject, "updatedTime", Date.class, date);
    }
}